/*
 * ==================================================
 * 项目开发者：JerryStark
 * 开发者Email：4771007@qq.com
 * 开发者QQ:4771007
 * 开发范围：web，wap，android,ios,osx or win or linux 应用
 * ==================================================
 */
package RTPower;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * 获得网卡地址类
 *
 * @author jerry
 */
public class RTMacAddress {

    /**
     * 获得网卡地址并返回文本
     *
     * @return
     */
    public static String Get() {
        StringBuilder back_macaddress = new StringBuilder();

        try {
            InetAddress address = InetAddress.getLocalHost();
            //InetAddress address = InetAddress.getByName("192.168.46.53");

            /*
             * Get NetworkInterface for the current host and then read the
             * hardware address.
             */
            NetworkInterface ni = NetworkInterface.getByInetAddress(address);
            if (ni != null) {
                byte[] mac = ni.getHardwareAddress();
                if (mac != null) {
                    /*
                     * Extract each array of mac address and convert it to hexa with the
                     * following format 08-00-27-DC-4A-9E.
                     */
                    for (int i = 0; i < mac.length; i++) {
//                        System.out.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
                        // mac[i] & 0xFF 是为了把byte转化为正整数
                        String s = Integer.toHexString(mac[i] & 0xFF);
                        back_macaddress.append(s.length() == 1 ? 0 + s : s);
                    }
                } else {
                    System.out.println("Address doesn't exist or is not accessible.");
                }
            } else {
                System.out.println("Network Interface for the specified address is not found.");
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return back_macaddress.toString();
    }
}
